import React from 'react';
import { withRouter, router } from 'umi';
import { Spin } from 'antd';
import { Toast } from 'antd-mobile';
import { useRequest, defaultFormatResult } from '@/hooks';
import { createForm } from 'rc-form';
import { InterviewDetail, Button, Password, Header, Tips } from './components';
import { useLogin } from '../hooks';
import { getLoginInfo, updatePassword } from '../service';

const Login = ({ form, location }) => {
    const { query } = location;
    const { getFieldProps } = form;
    const [submitLoading, setSubmitLoading] = React.useState(false);

    const { loading: loginLoading, handleLogin } = useLogin(query);

    const { data, loading, run: fetchDetail } = useRequest(() => getLoginInfo(query.id), {
        manual: true,
        initialData: null,
        ...defaultFormatResult
    });

    const list = [
        {
            key: '用户名称',
            value: data?.talentName || '--'
        },
        {
            key: '手机号',
            value: data?.talentPhone || '--'
        },
        {
            key: '账号',
            value: data?.talentEmail || '--'
        }
    ];

    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            // console.log('handleSubmit -> values', values);
            if (!err) {
                setSubmitLoading(true);
                if (data?.modifyPwdSafetyCode) {
                    updatePassword({
                        key: data?.modifyPwdSafetyCode,
                        password: values.password
                    })
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                handleLogin({
                                    talentEmail: data?.talentEmail || '',
                                    password: values.password
                                });
                            } else {
                                Toast.info(msg);
                                setSubmitLoading(false);
                            }
                        })
                        .catch(() => {
                            setSubmitLoading(false);
                        });
                } else {
                    handleLogin({
                        talentEmail: data?.talentEmail || '',
                        password: values.password
                    }).finally(() => setSubmitLoading(false));
                }
            }
            //  else {
            //     const tempList = Object.values(err);
            //     if (tempList && tempList.length > 0) {
            //         const { errors } = tempList[0];
            //         Toast.info(errors[0]?.message);
            //     }
            // }
        });
    };

    React.useEffect(() => {
        if (query?.id) {
            fetchDetail();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [query]);

    const isSetting = data?.modifyPwdSafetyCode;

    const detailStyle = {
        style: { marginBottom: 8 },
        keyStyle: {
            width: '5.5em',
            textAlign: 'right',
            fontSize: 14,
            color: '#858B9B',
            fontWeight: 500
        },
        valueStyle: {
            fontSize: 14,
            color: '#2A2F3C'
        }
    };

    const pageStyle = isSetting
        ? {}
        : {
              minHeight: '100%',
              background: '#fff'
          };

    return (
        <div style={pageStyle}>
            <Spin spinning={loading}>
                <div style={{ background: '#fff', marginBottom: isSetting ? 8 : 0 }}>
                    <Header />
                    {isSetting ? (
                        <Tips
                            title="已为您开通候选人帐号，请设置密码并登录"
                            content="该账号也将在后续应聘过程中使用，请妥善保管"
                        />
                    ) : (
                        <div
                            style={{
                                padding: '0 24px',
                                color: '#2A2F3C',
                                marginTop: 24,
                                fontSize: 20,
                                fontWeight: 600,
                                lineHeight: '32px'
                            }}
                        >
                            你好{data?.talentName ? '，' : ''}
                            {data?.talentName}
                        </div>
                    )}
                </div>
                <div style={{ background: '#fff', padding: isSetting ? 16 : 24 }}>
                    <div
                        style={{
                            background: '#fafafa',
                            padding: '16px 16px 8px 12px',
                            borderRadius: 4,
                            border: '1px solid #F2F3F4',
                            marginBottom: 20
                        }}
                    >
                        <InterviewDetail dataSource={list} {...detailStyle} />
                    </div>
                    <Password
                        label={isSetting ? '设置密码' : '密码'}
                        {...getFieldProps('password', {
                            rules: [
                                {
                                    required: true,
                                    whiteSpace: true,
                                    message: '请输入密码'
                                },
                                {
                                    validator(rule, value, callback) {
                                        const regex = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).*$/;
                                        if (value) {
                                            const tempValue = value.trim();
                                            if (!regex.test(value) && isSetting) {
                                                callback('密码需包含大小写英文及数字');
                                            } else if ((tempValue.length < 8 || tempValue.length > 20) && isSetting) {
                                                callback('密码8-20位');
                                            } else if (tempValue.length > 1 && tempValue.length < 8 && !isSetting) {
                                                callback('密码长度不少于 8 个字符！');
                                            } else {
                                                callback();
                                                if (form.getFieldValue('password2')) {
                                                    form.validateFields();
                                                }
                                            }
                                        }
                                        callback();
                                    }
                                }
                            ]
                        })}
                        error={form.getFieldError('password')}
                        errorText={form.getFieldError('password')}
                        placeholder="请输入密码"
                        maxLength={20}
                        clear
                    />
                    {isSetting && (
                        <Password
                            label="确认密码"
                            {...getFieldProps('password2', {
                                rules: [
                                    {
                                        required: true,
                                        whiteSpace: true,
                                        message: '请输入确认密码'
                                    },
                                    {
                                        validator(rule, value, callback) {
                                            if (value) {
                                                const tempValue = value.trim();
                                                const password = form.getFieldValue('password').trim();
                                                if (tempValue === password) {
                                                    callback();
                                                } else {
                                                    callback('两次输入的密码不相同');
                                                }
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })}
                            error={form.getFieldError('password2')}
                            errorText={form.getFieldError('password2')}
                            placeholder="请输入确认密码"
                            maxLength={20}
                            clear
                        />
                    )}
                    <Button
                        type="primary"
                        loading={submitLoading || loginLoading}
                        style={{ marginTop: 12 }}
                        onClick={handleSubmit}
                    >
                        {isSetting ? '设置并登录' : '登录'}
                    </Button>
                    {!isSetting && (
                        <div
                            style={{ padding: '12px 0', display: 'flex', justifyContent: 'flex-end' }}
                            onClick={() =>
                                history.push({
                                    pathname: '/external/interview/resetPassword',
                                    query: {
                                        id: query?.id,
                                        name: data?.talentName,
                                        email: data?.talentEmail
                                    }
                                })
                            }
                        >
                            <div style={{ color: '#2D87FF', fontSize: 14, lineHeight: '20px' }}>忘记密码</div>
                        </div>
                    )}
                </div>
            </Spin>
        </div>
    );
};

export default withRouter(createForm()(Login));
